package com.zhoulu.service.user;

import com.zhoulu.domain.user.UserBean;
import com.zhoulu.domain.user.UserRole;
import com.zhoulu.mapper.user.UsersMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.MessageFormat;
import java.util.List;


@Service
public class UserService {

    @Autowired
    private UsersMapper usersMapper;

    /**
     * 查询用户
     * @param userBean
     * @return
     */
    public UserBean queryUser(UserBean userBean){
        return usersMapper.queryUser(userBean);
    }

    /**
     * 修改密码
     * @param userBean
     */
    public void updatePassword(UserBean userBean){
        usersMapper.updatePassword(userBean);
    }

    /**
     * 查询用户权限列表
     * @param username 用户名
     * @return
     */
    public List<String> queryPermissionByUsername(String username){
        return usersMapper.queryPermissionByUsername(username);
    }

    /**
     * 新增用户
     * @param userBean
     */
    @Transactional(rollbackFor = Exception.class)
    public void insertUser(UserBean userBean){
        // 1、新增用户信息
        usersMapper.insertUser(userBean);
        // 2、查询role_id
        Integer roleId = usersMapper.getRoleIdByCode(userBean.getRoleCode());
        if(roleId == null){
            throw new RuntimeException(MessageFormat.format("角色code: {0}查询不到id", userBean.getRoleCode()));
        }
        // 3、新增用户角色映射
        UserRole userRole = new UserRole();
        userRole.setUserId(userBean.getId());
        userRole.setRoleId(roleId);
        usersMapper.insertUserRole(userRole);
    }
}
